﻿using B.S.BaseData.ErrorCode;
using B.S.BaseData.Manage.Api.Read.Apilaction.Command.StoreCommand;
using B.S.BaseData.Manage.Api.Read.DTO;
using DAL;
using MediatR;
using Microsoft.Data.SqlClient;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;

namespace B.S.BaseData.Manage.Api.Read.Apilaction.CoomandHandler.StoreCommandHandler
{
    public class StoreProductFileCommandHandler : IRequestHandler<StoreProductFileCommand, ApiReqult<List<StoreproductDTO>>>
    {
        private readonly DBHelper bHelper;

        public StoreProductFileCommandHandler(DBHelper bHelper)
        {
            this.bHelper = bHelper;
        }

        public async Task<ApiReqult<List<StoreproductDTO>>> Handle(StoreProductFileCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiReqult<List<StoreproductDTO>>();
            // 输出接收到的 ProductIds
            Debug.WriteLine($"接收到的 ProductIds: {string.Join(",", request.ProductIds ?? new List<int>())}");
            try
            {
                var productIds = request.ProductIds;
                if (productIds == null || productIds.Count == 0)
                {
                    result.Data = new List<StoreproductDTO>();
                    result.Code = ApiEnum.查询成功;
                    result.Msg = "查询成功，无查询条件";
                    return result;
                }

                var idList = string.Join(",", productIds);
                string sql = $"SELECT * FROM ManagementModels WHERE Id IN ({idList})";

                List<StoreproductDTO>? hoModes = bHelper.GetList<StoreproductDTO>(sql);

                if (hoModes != null && hoModes.Count > 0)
                {
                    result.Data = hoModes;
                    result.Code = ApiEnum.查询成功;
                    result.Msg = ApiEnum.查询成功.ToString();
                }
                else
                {
                    result.Data = new List<StoreproductDTO>();
                    result.Code = ApiEnum.查询失败;
                    result.Msg = ApiEnum.查询失败.ToString();
                }
            }
            catch (SqlException ex)
            {
                result.Data = new List<StoreproductDTO>();
                result.Code = ApiEnum.查询失败;
                result.Msg = $"SQL 查询失败: {ex.Message}";
                Debug.WriteLine($"SQL 错误: {ex.Message}");
            }
            catch (Exception ex)
            {
                result.Data = new List<StoreproductDTO>();
                result.Code = ApiEnum.查询失败;
                result.Msg = $"查询失败: {ex.Message}";
                Debug.WriteLine($"未知错误: {ex.Message}");
            }

            return result;
        }
    }
}